<script setup>
import { onMounted, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import SaveBrand from "./SaveBrand.vue";
import {router} from "../../router/index.js";
import {useRoute} from "vue-router";
import { Plus } from '@element-plus/icons-vue';

const formData = ref({});

const brandOptions = ref([]);
const unitOptions = ref([]);
const brandVisible = ref(false);
const uploadRef = ref();
const imageUrl = ref('');
const route = useRoute()

const handleAvatarSuccess = (resp) => {
  imageUrl.value = resp;
  formData.value.image = resp;
  ElMessage.success("上传成功");
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('您上传的头像必须是jpg或者png格式');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('您上传的图片大小必须2M以内');
    return false;
  }
  return true;
};

const handleConfirm = () => {
  axios.post("/carcenter-service-order/products/editProduct", formData.value).then(resp => {
    ElMessage.success(resp.data.message);
    router.push({name:'Product'})
  });
};

const handleCreateBrand = () => {
  brandVisible.value = true;
};

const getBrandVisible = (val) => {
  brandVisible.value = val;
};

watch(
    () => brandOptions.value,
    (newVal) => {
      if (!Array.isArray(newVal)) {
        console.error('brandOptions 不是数组:', newVal);
        brandOptions.value = [];
      }
    }
);

watch(
    () => unitOptions.value,
    (newVal) => {
      if (!Array.isArray(newVal)) {
        console.error('unitOptions 不是数组:', newVal);
        unitOptions.value = [];
      }
    }
);

const getBrands = () => {
  axios.get('/carcenter-service-order/product-brands/getDetail').then(resp => {
    if (Array.isArray(resp.data.data)) {
      brandOptions.value = resp.data.data.map(brand => ({
        label: brand.brandName,
        value: brand.id
      }));
    } else {
      brandOptions.value = [];
    }
  });
};

const getUnits = () => {
  axios.get(`/carcenter-service-order/units/getDetail`).then(resp => {
    if (Array.isArray(resp.data.data)) {
      unitOptions.value = resp.data.data.map(unit => ({
        label: unit.unitName,
        value: unit.id
      }));
    } else {
      unitOptions.value = [];
    }
  });
};

const getProductAndSpec = ()=>{
  axios.get(`/carcenter-service-order/products/getProductAndSpec/${route.query.id}`).then(resp => {
    formData.value = resp.data.data;
  })
};

onMounted(() => {
  getBrands();
  getUnits();
  getProductAndSpec();
});

</script>

<template>
  <div class="product-create-page">
    <el-container>
      <el-main>
        <!-- 商品基本信息部分 -->
        <div class="section">
          <h3 class="section-title">商品基本信息</h3>
          <el-form :model="formData" label-width="100px" class="form">
            <el-form-item label="商品名称">
              <el-input v-model="formData.productName" placeholder="请输入商品名称" style="width: 50%;" />
            </el-form-item>
            <el-form-item label="品牌">
              <el-row type="flex" justify="space-between" align="middle">
                <el-col :span="18">
                  <el-select v-model="formData.brandId" placeholder="请选择品牌" style="width: 100px;">
                    <el-option
                        v-for="item in brandOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-button type="text" @click="handleCreateBrand">新建品牌</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="单位">
              <el-select v-model="formData.unitId" placeholder="请选择单位" style="width: 50%;">
                <el-option
                    v-for="item in unitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <el-divider />

        <!-- 规格信息部分 -->
        <div class="section">
          <h3>规格信息</h3>
          <el-form :model="formData" label-width="120px" class="form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="粘度">
                  <el-input v-model="formData.viscosity" placeholder="请设置粘度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="重量">
                  <el-input v-model="formData.weight" placeholder="请设置重量" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="容量">
                  <el-input v-model="formData.capacity" placeholder="请设置容量" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="适配发动机">
                  <el-input v-model="formData.engineFit" placeholder="请设置适配发动机" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="基础油级别">
                  <el-input v-model="formData.baseOilLevel" placeholder="请设置基础油级别" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品级别">
                  <el-input v-model="formData.productLevel" placeholder="请设置产品级别" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 价格和库存信息 -->
        <div class="section">
          <el-form :model="formData" label-width="100px" class="form">
            <el-form-item label="标准价">
              <el-input v-model="formData.standardPrice" placeholder="标准价" style="width: 50%;" />
            </el-form-item>
            <el-form-item label="零售价">
              <el-input v-model="formData.retailPrice" placeholder="零售价" style="width: 50%;" />
            </el-form-item>
            <el-form-item label="成本价">
              <el-input v-model="formData.costPrice" placeholder="成本价" style="width: 50%;" />
            </el-form-item>
            <el-form-item label="库存">
              <el-input v-model="formData.inventory" placeholder="库存" style="width: 50%;" />
            </el-form-item>
            <el-form-item label="商品介绍">
              <el-input v-model="formData.productDescription" placeholder="请输入商品介绍" type="textarea" style="width: 50%;" />
            </el-form-item>
          </el-form>
        </div>

        <!-- 按钮 -->
        <div class="section">
          <el-button @click="$router.back()">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>

        <!-- 新建品牌组件 -->
        <SaveBrand :brandVisible="brandVisible" @brandDialogVisible="getBrandVisible" />
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
.product-create-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}
.section {
  margin-bottom: 30px;
}
.section-title {
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: bold;
}
.form {
  margin-bottom: 20px;
}
.specs-table {
  margin-bottom: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>